// 数据传递交互
var transmit = {
	cache: {},

	/**
	 * [send 发送消息, (id, data) 或 ([id1, id2...], data) 或 ({id: id, data: data})]
	 * @param {[type]} id [接收唯一标识]
	 * @param {[type]} data [发送的数据]
	 * @return {[type]} [无]
	 */
	send: function() {
		if (arguments) {
			if (arguments.length === 1 && 'Object' === Object.prototype.toString.call(arguments[0]).replace(/^\[object\s+|\]$/g, '')) {
				var obj = {
					id: arguments[0].id,
					time: new Date().getTime(),
					type: Object.prototype.toString.call(arguments[0].data).replace(/^\[object\s+|\]$/g, ''),
					data: arguments[0].data
				};
				this.cache[obj.id] = obj;
				top.postMessage(JSON.stringify(obj), '*');
			} else if (arguments.length >= 2) {
				var type = Object.prototype.toString.call(arguments[1]).replace(/^\[object\s+|\]$/g, '');
				if ('Array' === Object.prototype.toString.call(arguments[0]).replace(/^\[object\s+|\]$/g, '')) {
					for (var i = 0; i < arguments[0].length; i++) {
						var obj = {
							id: arguments[0][i],
							time: new Date().getTime(),
							type: type,
							data: arguments[1]
						};
						this.cache[obj.id] = obj;
						top.postMessage(JSON.stringify(obj), '*');
					}
				} else {
					var obj = {
						id: arguments[0],
						time: new Date().getTime(),
						type: type,
						data: arguments[1]
					};
					this.cache[obj.id] = obj;
					top.postMessage(JSON.stringify(obj), '*');
				}
			}
		}
	},

	/**
	 * [receive 接收消息]
	 * @param {[type]} id [唯一标识]
	 * @param {Function} callback [回调函数]
	 * @return {[type]} [无]
	 */
	receive: function(id, callback) {
		if (id) {
			if (typeof(callback) === 'function') {
				top.window.addEventListener('message', function(event) {
					var obj = JSON.parse(event.data),
						data = obj.data;
					if (obj.id === id) {
						callback(data, obj, event);
					}
				});

				if (this.cache[id]) {
					callback(this.cache[id].data, this.cache[id]);
				}
			}
			if (this.cache[id]) {
				return this.cache[id].data;
			}
		}
	},

	/**
	 * [clear 清除指定消息缓存 (id) 或 ([id1, id2...]) 或 (id1, id2...)]
	 * @return {[type]} [无]
	 */
	clear: function() {
		if (arguments && arguments.length > 0) {
			for (var i = 0; i < arguments.length; i++) {
				if (Object.prototype.toString.call(arguments[i]).replace(/^\[object\s+|\]$/g, '') === 'Array')
					for (var j = 0; j < arguments[i].length; j++) {
						if (this.cache[arguments[i][j]])
							delete this.cache[arguments[i][j]];
					}
				else if (this.cache[arguments[i]])
					delete this.cache[arguments[i]];
			}
		} else this.cache = {};
	}
}